package com.zoo.springbootinit.canal;

import com.zoo.springbootinit.exception.esdao.PostEsDao;
import com.zoo.springbootinit.model.dto.post.PostEsDTO;
import com.zoo.springbootinit.model.entity.Post;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import top.javatool.canal.client.annotation.CanalTable;
import top.javatool.canal.client.handler.EntryHandler;

import java.util.Arrays;

@Component
@CanalTable(value = "post")
@Slf4j
public class CanalHandler implements EntryHandler<Post> {

    @Autowired
    PostEsDao postEsDao;

    @Override
    public void insert(Post post) {
        PostEsDTO postEsDTO = new PostEsDTO();
        postEsDTO.setId(post.getId());
        postEsDTO.setTitle(post.getTitle());
        postEsDTO.setContent(post.getContent());
        String newTag = post.getTags().replace("[", "").replace("]", "").replace("\"", "");
        postEsDTO.setTags(Arrays.asList(StringUtils.split(newTag, ',')));
        postEsDTO.setThumbNum(post.getThumbNum());
        postEsDTO.setFavourNum(post.getFavourNum());
        postEsDTO.setUserId(post.getUserId());
        postEsDTO.setCreateTime(post.getCreateTime());
        postEsDTO.setUpdateTime(post.getUpdateTime());
        postEsDTO.setIsDelete(post.getIsDelete());
        postEsDao.save(postEsDTO);
        log.info("新增数据:{}", postEsDTO);
    }

    @Override
    public void update(Post before, Post after) {
        PostEsDTO postEsDTO = new PostEsDTO();
        postEsDTO.setId(after.getId());
        postEsDTO.setTitle(after.getTitle());
        postEsDTO.setContent(after.getContent());
        String newTag = after.getTags().replace("[", "").replace("]", "").replace("\"", "");
        postEsDTO.setTags(Arrays.asList(StringUtils.split(newTag, ',')));
        postEsDTO.setThumbNum(after.getThumbNum());
        postEsDTO.setFavourNum(after.getFavourNum());
        postEsDTO.setUserId(after.getUserId());
        postEsDTO.setCreateTime(after.getCreateTime());
        postEsDTO.setUpdateTime(after.getUpdateTime());
        postEsDTO.setIsDelete(after.getIsDelete());
        postEsDao.save(postEsDTO);
    }
    @Override
    public void delete(Post post) {
        postEsDao.deleteById(post.getId());
    }
}
